local Piece = require "packages.chess-games.xiangqi.core.piece"

local Cannon = Piece:subclass("Xiangqi.Cannon")

function Cannon:initialize(id)
  Piece.initialize(self, id)

  self.name = 'cannon'
  self.redStr = '炮'
  self.blackStr = '炮'
end

---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
function Cannon:canMoveTo(board, fromX, fromY, x, y)
  -- 不能移动到自己位置
  if fromX == x and fromY == y then
    return false
  end

  -- 必须同行或同列
  if fromX ~= x and fromY ~= y then
    return false
  end

  -- 统计路径上的棋子数
  local count = 0
  if fromX == x then
    -- 同列
    local step = (y > fromY) and 1 or -1
    for j = fromY + step, y - step, step do
      if board[j][x] ~= 0 then
        count = count + 1
      end
    end
  else
    -- 同行
    local step = (x > fromX) and 1 or -1
    for i = fromX + step, x - step, step do
      if board[fromY][i] ~= 0 then
        count = count + 1
      end
    end
  end

  local targetId = board[y][x]
  local myColor = self:getColor()

  if targetId == 0 then
    -- 目标为空格，必须无阻挡
    return count == 0
  else
    -- 目标有棋子，必须隔一个子才能打击
    if count ~= 1 then
      return false
    end
    -- 不能吃自己人
    local targetColor = (targetId > 0) and "red" or "black"
    return myColor ~= targetColor
  end
end

return Cannon

